package com.chenxin.interact.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.DeviceResult;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.enums.*;
import com.chenxin.common.exception.ServiceException;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.ToDeviceOrder;
import com.chenxin.interact.domain.dto.MovePositionDTO;
import com.chenxin.interact.domain.dto.SmtSaveSuccessDTO;
import com.chenxin.interact.domain.dto.SmtTakeSuccessDTO;
import com.chenxin.interact.domain.dto.StopOutputBusinessDTO;
import com.chenxin.interact.mapper.ToDeviceOrderMapper;
import com.chenxin.interact.service.ISmtToWmsService;
import com.chenxin.interact.service.IUrlMapService;
import com.chenxin.wms.domain.*;
import com.chenxin.wms.mapper.*;
import com.chenxin.wms.process.stock.impl.StockProcessImpl;
import com.chenxin.wms.service.IIbMasterService;
import com.chenxin.wms.service.IObMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * 智能仓服务实现
 *
 * @author chenxin
 * @date 2025-07-09
 */
@Service
@Slf4j
public class SmtToWmsServiceImpl implements ISmtToWmsService {

    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IbMasterMapper ibMasterMapper;
    @Autowired
    private IbDetailMapper ibDetailMapper;
    @Autowired
    private StockProcessImpl stockProcessImpl;
    @Autowired
    private ObMasterMapper obMasterMapper;
    @Autowired
    private ObDetailMapper obDetailMapper;
    @Autowired
    private IObMasterService obMasterService;
    @Autowired
    private IIbMasterService ibMasterService;
    @Autowired
    private IUrlMapService urlMapService;
    @Autowired
    private ToDeviceOrderMapper toDeviceOrderMapper;

    private final RestTemplate restTemplate;

    public SmtToWmsServiceImpl(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSuccess(SmtSaveSuccessDTO dto) {
        log.info("智能仓入库成功接口saveSuccess参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();
        //1.校验业务数据
        String positionCode = dto.getPositionCode();
        LocationEntity locationEntity = locationMapper.selectOne(new QueryWrapper<LocationEntity>().lambda().eq(LocationEntity::getLocationNo, positionCode).last("limit 1"));
        if (locationEntity == null) {
            throw new ServiceException("库位编码【" + positionCode + "】不存在！");
        }

//        String warehouseNo = dto.getTowerNo();
//        if (!warehouseNo.equals("DIP_WH")) {
//            throw new ServiceException("仓库编码【"+ warehouseNo + "】不是DIP智能仓！");
//        }
        String pn = dto.getPN();
        SpuEntity spuEntity = spuMapper.selectOne(new QueryWrapper<SpuEntity>().lambda().eq(SpuEntity::getSpuNo, pn).last("limit 1"));
        if (spuEntity == null) {
            throw new ServiceException("物料号【" + pn + "】不存在！");
        }

        String billNo = dto.getBillNo();
        IbMasterEntity ibMasterEntity = ibMasterMapper.selectOne(new QueryWrapper<IbMasterEntity>().lambda().eq(IbMasterEntity::getIbMasterNo, billNo).last("limit 1"));
        if (ibMasterEntity == null) {
            throw new ServiceException("入库单【" + billNo + "】不存在！");
        }
        //找到相应入库明细
        QueryWrapper<IbDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IbDetailEntity::getIbMasterId, ibMasterEntity.getIbMasterId())
                .eq(IbDetailEntity::getSpuNo, pn).last("limit 1");
        IbDetailEntity ibDetailEntity = ibDetailMapper.selectOne(queryWrapper);
        if (ibDetailEntity == null) {
            throw new ServiceException("入库单【"+ billNo + "】下不存在物料【"+ pn + "】的入库明细！");
        }
        //2.更新单据状态，添加库存，更新货位表
        //修改入库明细
        BigDecimal add = ibDetailEntity.getIbActualQty().add(new BigDecimal(dto.getQty()));
        IbDetailEntity updateIbDetail = new IbDetailEntity();
        updateIbDetail.setIbDetailId(ibDetailEntity.getIbDetailId());
        updateIbDetail.setIbActualQty(add);
        if (add.compareTo(ibDetailEntity.getIbPlanQty()) == 0) {
            updateIbDetail.setIbDetailStatus(WmsBusinessStatus.IB_DETAIL_DONE.getCode());
        } else {
            updateIbDetail.setIbDetailStatus(WmsBusinessStatus.IB_DETAIL_EXEC.getCode());
        }
        updateIbDetail.setUpdater(userId);
        updateIbDetail.setUpdateDate(startDate);
//        updateIbDetail.setComments(comment);
        try {
            ibDetailMapper.updateById(updateIbDetail);
        } catch (Exception e) {
            log.info("修改入库明细失败", e);
            throw new ServiceException("修改入库明细失败！");
        }
        //修改主单状态
        Map<String, Object> params = new HashMap<>();
        params.put("ibMasterId", ibDetailEntity.getIbMasterId());
//        params.put("comment", comment);
        params.put("userId", userId);
        //try {
        //    ibMasterService.ibMasterStatus(params);
        //} catch (Exception e) {
        //    log.info("修改主单失败", e);
        //    throw new ServiceException("修改主单失败！");
        //}

        StockEntity stockEntity = new StockEntity();
        stockEntity.setContNo(dto.getReelId());
        stockEntity.setLocationNo(positionCode);
        stockEntity.setSpuNo(pn);
        stockEntity.setLotNo(dto.getLot());
        stockEntity.setStockQty(new BigDecimal(dto.getQty()));
        stockEntity.setQualityStatus(!spuEntity.getIsQuality().equals("0") ? WmsConstants.STOCK_QA_A : WmsConstants.STOCK_QA_B);
        stockEntity.setIbDetailId(ibDetailEntity.getIbDetailId());
        stockEntity.setSupplierNo(dto.getSupplier());
        stockEntity.setReelId(dto.getReelId());
        stockEntity.setCreator(userId);

        // 写入库存
        ProcResult resultStock = stockProcessImpl.procWmsStockInsert(stockEntity);
        if (!resultStock.getCode().equals("0")) {
            throw new ServiceException("库存写入失败: " + resultStock.getMessage());
        }

        locationEntity.setContNo(dto.getReelId());
        locationEntity.setLocationStatus(WmsLocateStatus.Apply.getCode());
        locationEntity.setUpdater(userId);
        locationEntity.setUpdateDate(startDate);
        try {
            locationMapper.updateById(locationEntity);
        } catch (Exception e) {
            log.info("更新货位表失败", e);
            throw new ServiceException("更新货位表失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void takeSuccess(SmtTakeSuccessDTO dto) {
        log.info("智能仓出库成功接口takeSuccess参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();

        //1.校验业务数据
        String positionCode = dto.getPositionCode();
        LocationEntity locationEntity = locationMapper.selectOne(new QueryWrapper<LocationEntity>().lambda().eq(LocationEntity::getLocationNo, positionCode).last("limit 1"));
        if (locationEntity == null) {
            throw new ServiceException("库位编码【" + positionCode + "】不存在！");
        }

        String pn = dto.getPN();
        SpuEntity spuEntity = spuMapper.selectOne(new QueryWrapper<SpuEntity>().lambda().eq(SpuEntity::getSpuNo, pn).last("limit 1"));
        if (spuEntity == null) {
            throw new ServiceException("物料号【" + pn + "】不存在！");
        }

        String orderNo = dto.getOrderNo();
        ObMasterEntity obMasterEntity = obMasterMapper.selectOne(new QueryWrapper<ObMasterEntity>().lambda().eq(ObMasterEntity::getObMasterNo, orderNo).last("limit 1"));
        if (obMasterEntity == null) {
            throw new ServiceException("出库单【" + orderNo + "】不存在！");
        }

        //2.更新单据状态，删除库存，更新货位表
        //找到相应出库明细
        QueryWrapper<ObDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ObDetailEntity::getObMasterId, obMasterEntity.getObMasterId())
                .eq(ObDetailEntity::getSpuNo, pn).last("limit 1");
        ObDetailEntity updateOrderDetail = obDetailMapper.selectOne(queryWrapper);
        //出库实际需要累加
        BigDecimal curActlQty = updateOrderDetail.getObActualQty().add(new BigDecimal(dto.getQty()));
        updateOrderDetail.setObActualQty(curActlQty);
        updateOrderDetail.setObDetailStatus(WmsBusinessStatus.OB_DETAIL_DONE.getCode());
        updateOrderDetail.setUpdater(userId);
        updateOrderDetail.setUpdateDate(startDate);
//        updateOrderDetail.setComments(comment);
        try {
            obDetailMapper.updateById(updateOrderDetail);
        } catch (Exception e) {
            log.info("修改出库明细失败", e);
            throw new ServiceException("修改出库明细失败！");
        }
        //修改主单状态
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", obMasterEntity.getObMasterId());
//        params.put("comment", comment);
        params.put("userId", userId);
        //try {
        //    obMasterService.orderStatus(params);
        //} catch (Exception e) {
        //    log.info("修改主单失败", e);
        //    throw new ServiceException("修改主单失败！");
        //}

        List<StockEntity> stockEntities = stockMapper.selectList(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()));
        for (StockEntity stockEntity : stockEntities) {
            stockMapper.deleteById(stockEntity.getStockId());
        }

        locationEntity.setContNo("");
        locationEntity.setLocationStatus(WmsLocateStatus.FREE.getCode());
        locationEntity.setUpdater(userId);
        locationEntity.setUpdateDate(startDate);
        try {
            locationMapper.updateById(locationEntity);
        } catch (Exception e) {
            log.info("更新货位表失败", e);
            throw new ServiceException("更新货位表失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult allowInputWarehouse(SmtSaveSuccessDTO dto) {
        log.info("智能仓请求入库接口allowInputWarehouse参数：{}", dto.toString());
        Long userId = dto.getUserId();

        //1.根据供应商，物料号，查询是否存在相应的入库单
        String supplier = dto.getSupplier();
        List<IbMasterEntity> ibMasterEntities = ibMasterMapper.selectList(new QueryWrapper<IbMasterEntity>()
                .lambda().eq(IbMasterEntity::getSupplierNo, supplier));
        if (ibMasterEntities.size() == 0) {
            return DeviceResult.error("未找到可入库的订单，不允许入库！");
        }
        for (IbMasterEntity ibMasterEntity : ibMasterEntities) {
            List<Integer> ibDetailStList = new ArrayList<>();
            ibDetailStList.add(WmsBusinessStatus.IB_DETAIL_EXEC.getCode());
            ibDetailStList.add(WmsBusinessStatus.IB_DETAIL_INIT.getCode());
            QueryWrapper<IbDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(IbDetailEntity::getSpuNo, dto.getSN())
                    .eq(IbDetailEntity::getIbMasterId, ibMasterEntity.getIbMasterId())
                    .in(IbDetailEntity::getIbDetailStatus, ibDetailStList).last("limit 1");
            IbDetailEntity ibDetailEntity = ibDetailMapper.selectOne(queryWrapper);
            //如果找到该物料的入库单明细，则返回该入库单的编号
            if (ibDetailEntity != null) {
                Map<String, Object> params = new HashMap<>();
                params.put("c_billno", ibDetailEntity.getIbMasterNo());
                return DeviceResult.success("操作成功！",params);
            }
        }
        return DeviceResult.error("未找到可入库的明细，不允许入库！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult lockPosition(SmtSaveSuccessDTO dto) {
        log.info("智能仓锁定物料接口lockPosition参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();
        StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()).last("limit 1"));
        if (stockEntity == null) {
            return DeviceResult.error("未找到该物料，不允许锁定！");
        }
        if (stockEntity.getStockStatus() != WmsBusinessStatus.STOCK_INIT.getCode()) {
            return DeviceResult.error("该物料非空闲状态，不允许锁定！");
        }
        stockEntity.setLockStatus(WmsBusinessStatus.STOCK_FREEZE.getCode());
        stockEntity.setLockReason("智能仓锁定");
        stockEntity.setUpdater(userId);
        stockEntity.setUpdateDate(startDate);
        try {
            stockMapper.updateById(stockEntity);
        } catch (Exception e) {
            log.info("更新库存表失败", e);
            return DeviceResult.error("更新库存表失败！");
        }
        return DeviceResult.success("锁定成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult UnLockPosition(SmtSaveSuccessDTO dto) {
        log.info("智能仓解锁物料接口UnLockPosition参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();
        StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()).last("limit 1"));
        if (stockEntity == null) {
            return DeviceResult.error("未找到该物料，不允许解锁！");
        }
        if (stockEntity.getLockStatus() != WmsBusinessStatus.STOCK_FREEZE.getCode()) {
            return DeviceResult.error("该物料非锁定状态，不允许解锁！");
        }
        stockEntity.setLockStatus(WmsBusinessStatus.STOCK_INIT.getCode());
        stockEntity.setLockReason("");
        stockEntity.setUpdater(userId);
        stockEntity.setUpdateDate(startDate);
        try {
            stockMapper.updateById(stockEntity);
        } catch (Exception e) {
            log.info("更新库存表失败", e);
            return DeviceResult.error("更新库存表失败！");
        }
        return DeviceResult.success("解锁成功");
    }

    @Override
    public void postObMaster(ObMasterEntity obMasterEntity) {
        log.info("下发设备出库单接口postObMaster请求参数：{}", obMasterEntity.toString());

        UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("PostBom");
        if (urlMap == null || urlMap.getUrlAdr().isEmpty()) {
            log.info("【PostBom】未在【wms_url_map】表中配置!");
            throw new ServiceException("【PostBom】未在【wms_url_map】表中配置!");
        }
        //TODO
        String obMasterNo = obMasterEntity.getObMasterNo();
        List<ObDetailEntity> obDetailEntities = obDetailMapper.selectList(new QueryWrapper<ObDetailEntity>().lambda().eq(ObDetailEntity::getObMasterNo, obMasterNo));
        for (ObDetailEntity obDetailEntity : obDetailEntities) {
            ToDeviceOrder wmsToDeviceOrder = new ToDeviceOrder();
            wmsToDeviceOrder.setPriority(1);
            wmsToDeviceOrder.setType(obMasterEntity.getObMasterType());
            wmsToDeviceOrder.setSN(obDetailEntity.getSpuNo());
            wmsToDeviceOrder.setStatus(0);
            int insert = toDeviceOrderMapper.insertToDeviceOrder(wmsToDeviceOrder);
            if (insert < 1) {
                throw new ServiceException("下发设备出库单指令新增失败!");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult errorOut(SmtSaveSuccessDTO dto) {
        log.info("智能仓异常出库接口errorOut参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();

        //校验库存
        StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()).last("limit 1"));
        if (stockEntity == null) {
            return DeviceResult.error("库存中未找到该物料！");
        }
        stockMapper.deleteById(stockEntity);
        //清空货位
        LocationEntity locationEntity = locationMapper.selectOne(new QueryWrapper<LocationEntity>().lambda().eq(LocationEntity::getLocationNo, stockEntity.getLocationNo()).last("limit 1"));
        locationEntity.setContNo("");
        locationEntity.setLocationStatus(WmsLocateStatus.FREE.getCode());
        locationEntity.setUpdater(userId);
        locationEntity.setUpdateDate(startDate);

        try {
            locationMapper.updateById(locationEntity);
        } catch (Exception e) {
            log.info("更新货位表失败", e);
            return DeviceResult.error("WMS更新货位表失败！");
        }
        return DeviceResult.success("出库成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult stopOutputBusiness(StopOutputBusinessDTO dto) {
        log.info("删除工单业务接口stopOutputBusiness参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();

        //集合为空删除出库单所有物料，不为空删除出库单指定物料
        if (dto.getOutItemList().size() == 0) {
            List<ObDetailEntity> obDetailEntities = obDetailMapper.selectList(new QueryWrapper<ObDetailEntity>().lambda().eq(ObDetailEntity::getObMasterNo, dto.getWorkOrderId()));
            for (ObDetailEntity obDetailEntity : obDetailEntities) {
                //将此出库主单下所有明细状态改为取消
                obDetailEntity.setObDetailStatus(WmsBusinessStatus.OB_DETAIL_CANCEL.getCode());
                obDetailEntity.setUpdater(userId);
                obDetailEntity.setUpdateDate(startDate);
                obDetailMapper.updateById(obDetailEntity);
            }
            return DeviceResult.success("删除成功");
        } else {
            List<StopOutputBusinessDTO.OutItem> outItemList = dto.getOutItemList();
            for (StopOutputBusinessDTO.OutItem outItem : outItemList) {
                StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, outItem.getReelId()).last("limit 1"));

                //通过库存物料编码去找到相应出库明细，将其状态改为取消
                ObDetailEntity obDetailEntity = obDetailMapper.selectOne(new QueryWrapper<ObDetailEntity>().lambda().eq(ObDetailEntity::getSpuNo, stockEntity.getSpuNo()).eq(ObDetailEntity::getObMasterNo, dto.getWorkOrderId()));
                obDetailEntity.setObDetailStatus(WmsBusinessStatus.OB_DETAIL_CANCEL.getCode());
                obDetailEntity.setUpdater(userId);
                obDetailEntity.setUpdateDate(startDate);
                obDetailMapper.updateById(obDetailEntity);
            }
            return DeviceResult.success("删除成功");
        }
    }

    @Override
    public JSONObject storageUtilizationRate(String towerNo) {
        log.info("查询库存使用率接口storageUtilizationRate参数：{}", towerNo);
        //校验 url地址
        UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("StorageUtilizationRate");
        if (urlMap == null || urlMap.getUrlAdr().isEmpty()) {
            log.info("【StorageUtilizationRate】未在【wms_url_map】表中配置!");
            throw new ServiceException("【StorageUtilizationRate】未在【wms_url_map】表中配置!");
        }
        // 拼接 url
        String url = urlMap.getUrlAdr() + urlMap.getUriAdr();
        Map<String, Object> params = new HashMap<>();
        params.put("TowerNo", towerNo);

        //post请求
        DeviceResult respond = restTemplate.postForObject(url, params, DeviceResult.class);
        if (respond == null) {
            throw new ServiceException("【StorageUtilizationRate】请求失败!");
        }
        if (respond.getSuccess()) {
            log.info("【StorageUtilizationRate】请求成功!");
            return (JSONObject) respond.getData();
        } else {
            log.info("库位利用率请求失败!");
            throw new ServiceException("库位利用率请求失败!" + respond.getMsg());
        }
    }

    @Override
    public JSONObject takeStock(Map<String, String> params) {
        log.info("查询库存接口takeStock参数：{}", params.toString());
        //校验 url地址
        UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("TakeStock");
        if (urlMap == null || urlMap.getUrlAdr().isEmpty()) {
            log.info("【TakeStock】未在【wms_url_map】表中配置!");
            throw new ServiceException("【TakeStock】未在【wms_url_map】表中配置!");
        }
        String url = urlMap.getUrlAdr() + urlMap.getUriAdr();

        //post请求
        DeviceResult respond = restTemplate.postForObject(url, params, DeviceResult.class);
        if (respond == null) {
            throw new ServiceException("【TakeStock】请求失败!");
        }
        if (respond.getSuccess()) {
            log.info("库存查询请求成功!");
            return (JSONObject) respond.getData();
        } else {
            log.info("库存查询请求失败!");
            throw new ServiceException("库存查询请求失败!" + respond.getMsg());
        }
    }

    @Override
    public JSONObject requestStatus(String towerNo) {
        log.info("查询设备状态接口requestStatus参数：{}", towerNo);
        //校验 url地址
        UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("requestStatus");
        if (urlMap == null || urlMap.getUrlAdr().isEmpty()) {
            log.info("【requestStatus】未在【wms_url_map】表中配置!");
            throw new ServiceException("【requestStatus】未在【wms_url_map】表中配置!");
        }
        String url = urlMap.getUrlAdr() + urlMap.getUriAdr();
        Map<String, Object> params = new HashMap<>();
        params.put("TowerNo", towerNo);

        //post请求
        DeviceResult respond = restTemplate.postForObject(url, params, DeviceResult.class);
        if (respond == null) {
            throw new ServiceException("【requestStatus】请求失败!");
        }
        if (respond.getSuccess()) {
            log.info("【requestStatus】请求成功!");
            return (JSONObject) respond.getData();
        } else {
            log.info("查询设备状态失败!");
            throw new ServiceException("查询设备状态失败!" + respond.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceResult movePosition(MovePositionDTO dto) {
        log.info("双升移库接口movePosition参数：{}", dto.toString());
        Long userId = dto.getUserId();
        Date startDate = new Date();

        //1.校验业务数据
        String positionCode = dto.getPositionCode();
        LocationEntity locationEntity = locationMapper.selectOne(new QueryWrapper<LocationEntity>().lambda().eq(LocationEntity::getLocationNo, positionCode).last("limit 1"));
        if (locationEntity == null) {
            return DeviceResult.error("库位编码【"+ positionCode + "】不存在！");
        }
        //中转方向 “I” In 表示 中转入 “O” Out 表示中转出
        if (dto.getTransferType().equals("I")) {
            //更新库存和货位数据
            StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()).last("limit 1"));
            stockEntity.setLocationNo(positionCode);
            stockEntity.setUpdater(userId);
            stockEntity.setUpdateDate(startDate);
            int stock = stockMapper.updateById(stockEntity);

            if (stock != 1) {
                return DeviceResult.error("库存更新失败!");
            }

            locationEntity.setContNo(dto.getReelId());
            locationEntity.setLocationStatus(WmsLocateStatus.Apply.getCode());
            locationEntity.setUpdater(userId);
            locationEntity.setUpdateDate(startDate);
            try {
                locationMapper.updateById(locationEntity);
            } catch (Exception e) {
                log.info("更新货位表失败", e);
                return DeviceResult.error("更新货位表失败！");
            }
        } else if (dto.getTransferType().equals("O")) {
            StockEntity stockEntity = stockMapper.selectOne(new QueryWrapper<StockEntity>().lambda().eq(StockEntity::getReelId, dto.getReelId()).last("limit 1"));
            stockEntity.setLocationNo("");
            stockEntity.setUpdater(userId);
            stockEntity.setUpdateDate(startDate);
            int stock = stockMapper.updateById(stockEntity);

            if (stock != 1) {
                return DeviceResult.error("库存更新失败!");
            }

            locationEntity.setContNo("");
            locationEntity.setLocationStatus(WmsLocateStatus.FREE.getCode());
            locationEntity.setUpdater(userId);
            locationEntity.setUpdateDate(startDate);
            try {
                locationMapper.updateById(locationEntity);
            } catch (Exception e) {
                log.info("更新货位表失败", e);
                return DeviceResult.error("更新货位表失败！");
            }
        }

        return DeviceResult.error("中转方向参数错误！");
    }
}
